<script setup lang="ts">
import _9png from './ic_launcher.9.png'
import NinePatch from './NinePatch'
import { onMounted, ref, useTemplateRef, watch } from 'vue'
import { useElementSize, useDebounceFn } from '@vueuse/core'
const el = useTemplateRef('el')
const { width, height } = useElementSize(el)

const style = ref({})

let ninePatch: NinePatch
const initNinePatch = async () => {
  if (!ninePatch) {
    ninePatch = new NinePatch(_9png)
    await ninePatch.init()
  }
}
const setBackground = async () => {
  const startTime = new Date().getTime()
  const _width = width.value
  const _height = height.value
  await initNinePatch()
  if (_width && _height && ninePatch) {
    const base64 = ninePatch.getBase64(_width, _height)
    // const base64 = ninePatch.getBase64(50, 50)
    console.log({ base64 })
    style.value = {
      backgroundImage: base64 ? `url('${base64}')` : '',
    }
  }
  console.log('耗时:' + (new Date().getTime() - startTime))
}
const setBackgroundThrottle = useDebounceFn(setBackground, 300)
watch([width, height], setBackgroundThrottle)
onMounted(setBackground)
</script>

<template>
  <div>
    <textarea ref="el" :style="style" class="nine-patch" v-text="width+','+height" />
    <div style="width: 100%; height: 400px; background-color: darkgrey" :style="style">{{ width }},{{ height }}</div>
  </div>
</template>

<style scoped>
.nine-patch {
  background-position: center;
  background-repeat: no-repeat;
  background-size: 100% 100%;
}
</style>
